package com.aaa.controller;

import com.aaa.excel.DemoDataListener;
import com.aaa.excel.ExcelDemo;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: qy158-system
 * @description:
 * @author: 闫克起2
 * @create: 2022-10-15 09:38
 **/
@Controller
public class ExcelController {


    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        List<ExcelDemo> data=new ArrayList<>();
        data.add(new ExcelDemo("王俊凯",17,"男","北京"));
        data.add(new ExcelDemo("王源",18,"男","商丘"));
        data.add(new ExcelDemo("易烊千玺",18,"男","郑州"));
        data.add(new ExcelDemo("王一博",19,"男","郑州"));
        EasyExcel.write(response.getOutputStream(), ExcelDemo.class).sheet("模板").doWrite(data);
    }
    @Autowired
    private DemoDAO demoDAO;

    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException{
        EasyExcel.read(file.getInputStream(), ExcelDemo.class, new DemoDataListener(demoDAO)).sheet().doRead();
        return "success";
    }
}
